import BaseService from "../basic/BaseService";
import enums from "../basic/enums";
import Const from "../Const";
import IdUtil from "../basic/utils/IdUtil";
import treeIcon from '../assets/styles/img/tree'

/**
 * 创建人：Dada.
 * 创建时间：2021年07月26日22:45:59
 */
export default class IndexService extends BaseService {

    //给用户生成默认文件数据
    generationDefaultFileData() {
        //生成树
        let treeList = [{
            _id: Const.db_id_prefix_tree + '0memo',
            name: '我的备忘',
            extName: '',
            pId: '',
            type: enums.FileType.package
        }, {
            _id: Const.db_id_prefix_tree + '0inspiration',
            name: '我的灵感',
            extName: '',
            pId: '',
            type: enums.FileType.package
        }, {
            _id: Const.db_id_prefix_tree + '0work',
            name: '我的工作',
            extName: '',
            pId: '',
            type: enums.FileType.package
        }, {
            _id: Const.db_id_prefix_tree + '0note',
            name: '我的笔记',
            extName: '',
            pId: '',
            type: enums.FileType.package
        },
            {
                _id: Const.db_id_prefix_tree + '0memo/1',
                contentId: Const.db_id_prefix_content + '4',
                name: '备忘示例.txt',
                extName: '.txt',
                pId: Const.db_id_prefix_tree + '0memo',
                type: enums.FileType.file
            }, {
                _id: Const.db_id_prefix_tree + '0inspiration/1',
                contentId: Const.db_id_prefix_content + '3',
                name: '灵感示例.txt',
                extName: '.txt',
                pId: Const.db_id_prefix_tree + '0inspiration',
                type: enums.FileType.file
            }, {
                _id: Const.db_id_prefix_tree + '0work/1',
                contentId: Const.db_id_prefix_content + '2',
                name: '工作示例.txt',
                extName: '.txt',
                pId: Const.db_id_prefix_tree + '0work',
                type: enums.FileType.file
            }, {
                _id: Const.db_id_prefix_tree + '0note/1',
                contentId: Const.db_id_prefix_content + '1',
                name: '笔记示例.txt',
                extName: '.txt',
                pId: Const.db_id_prefix_tree + '0note',
                type: enums.FileType.file
            }];

        let contentList = [{
            _id: Const.db_id_prefix_content + '1',
            content: '笔记示例',
        }, {
            _id: Const.db_id_prefix_content + '2',
            content: '工作示例',
        }, {
            _id: Const.db_id_prefix_content + '3',
            content: '灵感示例',
        }, {
            _id: Const.db_id_prefix_content + '4',
            content: '备忘示例',
        }];
        let id = "isOneStart";
        let isOneStart = this.get(id);
        if (isOneStart && isOneStart.data === 1) {
            return;
        }
        this.batchSave(treeList.concat(contentList));
        this.save({
            _id: id,
            data: 1
        })
    }

    //获取文件树
    findFileTree() {
        let list = this.getList(Const.db_id_prefix_tree);
        list.map(item => this.procItemToZtreeNode(item));
        return list;
    }

    //把节点加工成功ztree的节点（把没有的属性加上）
    procItemToZtreeNode(item) {
        let icon = treeIcon.getFileIcon();
        switch (item.type) {
            case enums.FileType.package:
                icon = treeIcon.getBaseIcon();
                break;
            case enums.FileType.file:
                icon = treeIcon.getFileIcon();
                break;
        }
        item.icon = icon;
        return item;
    }

    //根据文件获取文件内容
    findFileContentByCId(contentId) {
        let contentList = this.getList(contentId);
        if (contentList.length === 0) {
            return null;
        }
        let contentObj = contentList[0];
        for (let i = 1; i < contentList.length; i++) {
            contentObj.content += contentList[i].content;
        }
        return contentObj
    }

    //根据ID获取节点
    findNodeById(id) {
        return this.get(id);
    }

    //判断这个文件名称在这个目录里面是否存在了
    fileNameInPath(name, pathId) {
        let list = this.getList(pathId);
        for (let item of list) {
            if (item.name == name) {
                return true;
            }
        }
        return false;
    }

    //重命名
    renameFile(id, name) {
        let item = this.get(id);
        if (!item) {
            throw new Error("目标不存在");
        }
        if (item.name === name) {
            return item._rev;
        }
        if (this.fileNameInPath(name, item.pId)) {
            throw new Error("文件名重复");
        }
        item.name = name;
        item.extName = name.substr(name.lastIndexOf('.'));
        let res = this.save(item);
        if (res.ok) {
            return res.rev;
        }
        throw new Error("重命名失败");
    }

    //保存文件内容
    saveFileContent(item) {
        let oneM = (1024 * 1024) / 2;
        //如果内容大于1M，则分段存储
        if (item.content.length / oneM > 1) {
            let strArr = [];
            for (let i = 0; i < item.content.length; i += oneM) {
                strArr.push(item.content.slice(i, i + oneM))
            }
            let cList = this.getList(item.contentId);
            cList.map(item => {
                this.delete(item._id);
            })
            for (let i = 0; i < strArr.length; i++) {
                let content = strArr[i];
                let cItem = {
                    _id: item.contentId + '/' + i,
                    content: content
                }
                this.save(cItem);
            }
        } else {
            let cItem = this.get(item.contentId);
            cItem.content = item.content;
            this.save(cItem);
        }
    }

    //删除文件
    deleteNode(id) {
        let node = this.findNodeById(id);
        if (!node) {
            throw new Error("数据不存在");
        }
        this.delete(node.contentId);
        this.delete(node._id);
    }

    /**
     * 新增文件 or 文件夹
     * @param name
     * @param type
     * @param defaultContent
     */
    addItem(pid, name, type, defaultContent) {
        if (pid) {
            let node = this.findNodeById(pid);
            if (!node) {
                pid = '';
            }
            if (node.type === enums.FileType.file) {
                pid = node.pId;
            }
        } else {
            pid = Const.db_id_prefix_tree;
        }

        let itemId = pid + new Date().getTime();
        let contentId = '';
        let extName = '';

        if (this.fileNameInPath(name, pid)) {
            throw new Error("名称重复");
        }

        if (type == enums.FileType.file) {
            let dotIndex = name.lastIndexOf('.');
            if (dotIndex === -1) {
                dotIndex = name.length;
            }
            extName = name.substr(dotIndex);
            if (!extName) {
                extName = '.txt';
                name += extName;
            }
            contentId = Const.db_id_prefix_content + new Date().getTime();
            let contentItem = {
                _id: contentId,
                content: defaultContent
            }
            this.save(contentItem);
        }

        let item = {
            _id: itemId,
            pId: pid,
            name: name,
            type: type,
            extName: extName,
            contentId: contentId
        }
        this.save(item);
        return item;
    }

    /**
     * 保存配置
     * @param config
     */
    config(config) {
        const defConfig = {
            [Const.config_key_init_tree_width]: 200,
        }
        if (!config) {
            let oldConfig = this.get(Const.db_config_key);
            if (!oldConfig) {
                this.save({
                    _id: Const.db_config_key,
                    ...Object.assign({}, defConfig)
                });
            }
            return this.get(Const.db_config_key);
        }
        let oldConfig = this.get(Const.db_config_key) || {};
        let newConfig = Object.assign({}, oldConfig, defConfig, config);
        this.save({
            _id: Const.db_config_key,
            ...newConfig
        });
    }
}